package com.kaishengit.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import com.kaishengit.entity.Account;
import com.kaishengit.util.DBHelp;
import com.kaishengit.util.RowMapper;

public class AccountDao {

	private DBHelp<Account> db = new DBHelp<Account>();
	
	public Account findById(int id) {
		String sql = "select id,username,password,money,enable,cookiepassword from t_account where id = ?";
		return db.executeQueryForObject(sql, new AccountRowMapper(), id);
	}
	
	public List<Account> findAll() {
		String sql = "select id,username,password,money,enable,cookiepassword from t_account";
		return db.executeQueryForList(sql, new AccountRowMapper());
	}
	
	public void save(Account a){
		String sql = "insert into t_account(username,password,money,enable)values(?,?,?,?)";
		db.executeSQL(sql, a.getUsername(),a.getPassword(),a.getMoney(),a.isEnable());
	}
	
	
	public Account findByNameAndPwd(String name,String pwd) {
		String sql = "select id,username,password,money,enable,cookiepassword from t_account where username = ? and password = ?";
		return db.executeQueryForObject(sql, new AccountRowMapper(), name,pwd);
	}
	
	public Account findByNameAndCookiepwd(String name,String cookiepwd) {
		String sql = "select id,username,password,money,enable,cookiepassword from t_account where username = ? and cookiepassword = ?";
		return db.executeQueryForObject(sql, new AccountRowMapper(), name,cookiepwd);
	}
	public void update(Account acc) {
		String sql = "update t_account set username = ?,password=?,money=?,enable=?,cookiepassword=? where id = ?";
		db.executeSQL(sql, acc.getUsername(),acc.getPassword(),acc.getMoney(),acc.isEnable(),acc.getCookiepassword(),acc.getId());
	}
	
	public Account findByName(String name) {
		String sql = "select id,username,password,money,enable,cookiepassword from t_account where username = ?";
		return db.executeQueryForObject(sql, new AccountRowMapper(), name);
	}
	
	
	
	private class AccountRowMapper implements RowMapper<Account> {

		public Account mapperRow(ResultSet rs) throws SQLException {
			Account account = new Account();
			account.setEnable(rs.getBoolean("enable"));
			account.setId(rs.getInt("id"));
			account.setMoney(rs.getFloat("money"));
			account.setPassword(rs.getString("password"));
			account.setUsername(rs.getString("username"));
			account.setCookiepassword(rs.getString("cookiepassword"));
			return account;
		}
		
	}
}
